// pages/detail/detail.js
const app = getApp();
const url = app.globalData.url;
const common = require("../../utils/common.js");
//引入图片预加载组件
const ImgLoader = require('../../template/img-loader/img-loader.js')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    pllist:[],
    loding:true,
    imgList:[],
    gms:true,
    url : app.globalData.url,
    plh: 30,
    pls:false,
    pldt:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    console.log(o)
    if(o.id){
      this.setData({id:o.id});
      this.imgLoader = new ImgLoader(this, this.imageOnLoad.bind(this))
      this.peizi();
    }else{
      this.setData({ loding: false })
      wx.showModal({
        title: "提示",
        content: "数据出错",
        showCancel: false,//是否显示取消按钮
        // cancelText: btn[0],//默认是“确定”
        confirmText: "确定",//默认是“确定”
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            // if (options.finish) {
            // }
          } else {
            wx.navigateBack({
              delta: 1,
              fail() {
                wx.redirectTo({
                  url: "/pages/index/index"
                })
              }
            })
          }
        },
        fail: function (res) { },//接口调用失败的回调函数
        complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
      })
    }
  },
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  isdel(e){
    let that=this;
    let sj={
      did:that.data.detail.did,
      issh:e.currentTarget.dataset.isd,
      uid:that.data.user.uid,
      uname:that.data.user.uname?that.data.user.uname:that.data.user.nickName,
      tt:that.data.detail.title,
      lx:"小程序端,详情展示处",
    };
    app.fetch('api/wx/upxq',sj, "POST", (err, data) => {
      console.log(data)
      if(data.code==200){
        wx.showToast({
          title: "操作成功",
          icon: 'success',
          duration: 1000
        });
        setTimeout(function () {
          wx.navigateBack({
            data: 1,
            fail(){
              wx.redirectTo({
                url: '/pages/index/index'
              })
            }
          })
        }, 1000)
      }else{
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/upxq' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            wx.navigateBack({
              data: 1,
              fail(){
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          },
        })
      }
    })
  },
  jzgdbtn(){
    var that = this;
      var count = that.data.pcount;
      var pno = that.data.pno;
      console.log(pno, count)
      if (pno - 1 < count) {
        wx.showLoading({
          title: "正在加载中....",
          // mask: true
        });
        that.getplb('sx');
      }
  },
  qx(){
    this.setData({ pls: false, value: ''});
  },
  //获取列表
  hqlist() {
    let that = this;
    let list = []
    let pno = 1;
    let sj = {
      pno: pno,
      fid: that.data.detail.fid,
      pgs: 5,
      sq:' AND did!='+that.data.detail.did,
    };
    app.fetch('api/wx/getxqlist', sj, "POST", (err, data) => {
      console.log(data)
      for (var i = 0; i < data.data.length; i++) {
        if (data.data[i].ewm) {
          data.data[i].ewm = url + data.data[i].ewm;
        }
        data.data[i].addtime = common.bijiao(data.data[i].addtime);
        if (data.data[i].logolist) {
          var arr = data.data[i].logolist.split(",");
          data.data[i].logolist = [];
          let ls = arr.length < 5 ? arr.length : 5;
          for (let a = 0; a < ls; a++) {
            data.data[i].logolist.push(url + arr[a]);
          }
        } else {
          data.data[i].logolist = [];
          // data[i].imgs.push(data[i].tx);
        };
        list.push(data.data[i]);
      }
      that.setData({
        xglist: list,
      });
    })
  },
  //失去焦点时
  bindblur: function (e) {
    this.setData({ value: this.trim(e.detail.value) })
  },
  subtn(e){
    this.setData({ value:e.detail.value})
  },
  addbtn(){
    let that=this;
    let pt=this.data.pldt;
    let sj={
      did:this.data.detail.did,
      duid:this.data.detail.uid,
      touid:this.data.user.uid,
      gouid: this.data.gouid,
      datalr:this.data.value
    };
    app.fetch('api/wx/addpl', sj, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.showToast({
          title: data.msg,
          icon: 'success',
          duration: 3000
        });
        that.setData({ pls: false,value:''});
        that.getplb();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/addpl' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  getplb(sx){
    let that = this;
    let list = []
    let pno = 1;
    let sq = '';
    if (sx) {
      list = that.data.pllist;
      pno = that.data.pno;
    }
    let sj = {
      pno: pno,
      pgs: 10,
      sq: sq,
      did: that.data.detail.did
    };
    app.fetch('api/wx/getpl', sj, "POST", (err, data) => {
      console.log(data)
      wx.hideLoading();
      if(data.code==200){
        for (var i = 0; i < data.list.length; i++) {
          data.list[i].addtime = common.bijiao(data.list[i].addtime);
          list.push(data.list[i]);
        }
        that.setData({
          pllist: list,
          pno: Number(data.pno) + 1,
          pcount: Number(data.pageCount),
        });
      }
    })
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    let that = this;
    if (that.data.pls || that.data.value) {
      //  console.log("执行清除")
      that.setData({
        pls: false,
        value: '',
      });
    }
  },
  ptsbtn(e){
    console.log(e)
    console.log(e.currentTarget.dataset.gid)
    let gid = e.currentTarget.dataset.gid;
    this.setData({
      gouid: gid,
      pls:true
    })
  },
  //放大图片
  previewImage: function (e) {
    var src = e.currentTarget.dataset.src; //获取data-src
    var imgList = this.data.imgList; //获取data-list
    //要把对象中需要的键值对拿出来，放进一个数组，Object.keys是为了取到对象的长度进行遍历
    var imgArr = [];
    var objkeys = Object.keys(imgList);
    for (var i = 0; i < objkeys.length; i++) {
      imgArr.push(imgList[i].url);
    }
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgArr // 需要预览的图片http链接列表
    })
  },
  ckewm(){
    wx.previewImage({
      urls: [this.data.detail.ewm],
      current: this.data.detail.ewm
    });
  },
  tourl(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },
  loadImages() {
    //同时发起全部图片的加载 
    this.data.imgList.forEach(item => {
      this.imgLoader.load(item.url)
    })
  },
  //加载完成后的回调
  imageOnLoad(err, data) {
    console.log('图片加载完成', err, data.src)

    const imgList = this.data.imgList.map(item => {
      if (item.url == data.src)
        item.loaded = true
      return item
    })
    this.setData({ imgList })
  },
  // 配置文件
  peizi: function () {
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxadd' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        data.data.xcx.tyewm.txt=url+data.data.xcx.tyewm.txt;
        that.setData({
          peizi: data.data,
        });
        that.setData({ loding: false })
        that.hquser();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  gmbtn(){
    wx.showLoading({
      title: '正在查询购买状态',
      mask:true
    })
    let that=this;
    let sj={
      did:that.data.id,
      uid:that.data.user.uid
    };
    let gly=that.data.user.isqx==1?false:true;
    let jbwk=that.data.detail.jb == 0 && that.data.peizi.xcx.ptjb.txt==0?true:false;
    if (that.data.user.uid==that.data.detail.uid||gly||jbwk){
      that.setData({ gms: false })
      wx.hideLoading();
    }else{
      app.fetch('api/wx/getgmb', sj, "POST", (err, data) => {
        wx.hideLoading();
        if(data.code==500){
          wx.showModal({
            title: '接口数据错误',
            content: '接口:"' + url + 'api/wx/getgmb' + '",msg:' + data.msg,
            showCancel: false,//是否显示取消按钮
            confirmText: "好的",//默认是“确定”
            confirmColor: 'skyblue',//确定文字的颜色
            success: function (res) {
              wx.navigateBack({
                data: 1,
                fail(){
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              })
            },
          })
        }else if (data.code == 400) {
          if (that.data.user.mfgm>0){
            wx.showModal({
              title: '提示',
              content: '免 ' + that.data.peizi.xcx.jb.txt + ' 次数还有 ' + that.data.user.mfgm+' 次，将要消耗一次免' + that.data.peizi.xcx.jb.txt + '购买该二维码 ',
              showCancel: true,//是否显示取消按钮
              cancelfirmText: "取消",//默认是“确定”
              confirmText: "购买",//默认是“确定”
              confirmColor: 'skyblue',//确定文字的颜色
              success: function (res) {
                if (res.cancel) {
                  //点击取消,默认隐藏弹框

                  // }
                } else {
                  let addsj={
                    uid:that.data.user.uid,
                    did:that.data.detail.did,
                    gmjb:0,
                    mfgm: that.data.user.mfgm-1
                  };
                  that.addgmb(addsj)
                }
              },
            })
          }else{
            var jb = (that.data.detail.jb == 0 ? that.data.peizi.xcx.ptjb.txt : that.data.detail.jb);
            var vipjb = jb * that.data.peizi.xcx.vipgmzk.txt;
            var xfjb=jb;
            if(that.data.user.vip==2){
              xfjb=vipjb;
            }
            xfjb=parseFloat(xfjb);
            var userjb=parseFloat(that.data.user.jb);
            console.log(userjb);
            console.log(xfjb)
            console.log(userjb>=xfjb)
            if(userjb>=xfjb){
              wx.showModal({
                title: '提示',
                content: '将要花费：' + jb + '个' + that.data.peizi.xcx.jb.txt + ' 购买该二维码。' + (that.data.peizi.xcx.vipgmzk.txt != 1 ? 'VIP只需：' + vipjb + '个' + that.data.peizi.xcx.jb.txt:''),
                showCancel: true,//是否显示取消按钮
                cancelfirmText: "取消",//默认是“确定”
                confirmText: "购买",//默认是“确定”
                confirmColor: 'skyblue',//确定文字的颜色
                success: function (res) {
                  if (res.cancel) {
                    //点击取消,默认隐藏弹框
                  
                    // }
                  } else {
                    var tt = '购买二维码消耗了' + xfjb + "个" + that.data.peizi.xcx.jb.txt;
                    var tt1 = '二维码赚取了' + (xfjb - (xfjb*that.data.peizi.xcx.ptss.txt)).toFixed(2) + "个" + that.data.peizi.xcx.jb.txt;
                    that.czjb(that.data.user.uid, 2, xfjb, tt, "购买二维码");
                    if(that.data.detail.jb != 0){
                      that.czjb(that.data.detail.uid, 1, (xfjb - (xfjb*that.data.peizi.xcx.ptss.txt)).toFixed(2), tt1, "二维码赚取");
                    }
                    let addsj = {
                      uid: that.data.user.uid,
                      did: that.data.detail.did,
                      gmjb: xfjb,
                    };
                    that.addgmb(addsj);
                  }
                },
              })
            }else{
              wx.showModal({
                title: '提示',
                content: '当前：'+that.data.user.jb+ that.data.peizi.xcx.jb.txt+ ' ，购买该二维码。需要' + xfjb + that.data.peizi.xcx.jb.txt,
                showCancel: true,//是否显示取消按钮
                cancelfirmText: "取消",//默认是“确定”
                confirmText: "充值",//默认是“确定”
                confirmColor: 'skyblue',//确定文字的颜色
                success: function (res) {
                  if (res.cancel) {
                    //点击取消,默认隐藏弹框
                  
                    // }
                  } else {
                    wx.navigateTo({
                      url: '/pages/qianb/qianb',
                    })
                  }
                },
              })
            }
          }
        }else if (data.code == 200) {
          that.setData({gms:false})
        }
      })
    }
  },
  addgmb(addsj){
    let that=this;
    app.fetch('api/wx/addgmb', addsj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        that.setData({ gms: false })
      } else {
        wx.showModal({
          title: '提示',
          content: data.msg,
        })
      }
    })
  },
  czjb(uid,sz, jb, tt, xlx) {
    let that = this;
    let sj = {
      uid:uid,
      sz: sz,
      jb: jb,
      tt: tt,
      lx: 'xcx',
      xlx: xlx ? xlx : ''
    };
    app.fetch('api/wx/czjb', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        // that.hquser();
      }
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0]})
            that.hqxq();
          }
        })
      },
      fail(){
        wx.showModal({
          title: '提示',
          content: '请先登录',
          success(res){
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              // if (options.finish) {
                wx.navigateBack({ delta: 1 })
              // }
            } else {
                wx.redirectTo({
                  url: "/pages/my/my"
                })
            }
          }
        })
      }
    })
  },
  hqxq(){
    let that=this;
    let sj={
      ckid:that.data.user.uid,
      id:that.data.id,
      isqx:that.data.user.isqx,
    };
    app.fetch('api/wx/getdetail', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        console.log(data);
        wx.setNavigationBarTitle({
          title: data.dt.title
        });
        data.dt.uptp = data.dt.logolist.split(",");
        data.dt.ystp = data.dt.logoyslist.split(",");
        let imgList = that.data.imgList;
        for (let i = 0; i < data.dt.uptp.length;i++){
          let imgList1 = { url: url + data.dt.uptp[i], ys: url + data.dt.ystp[i], loaded: false };
          imgList.push(imgList1);
        }
        data.dt.ewm = url + data.dt.ewm;
        data.dt.xgtime = common.format(data.dt.xgtime)
        data.dt.addtime = common.format(data.dt.addtime)
        that.setData({ detail: data.dt, imgList: imgList });
        that.loadImages();
        that.getplb();
        that.hqlist();
        // that.setData({ user: data.data[0] })
      }else if (data.code == 400) {
        wx.showModal({
          title: '提示',
          content: data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            wx.navigateBack({
              data: 1,
              fail(){
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          },
        })
      }else{
        wx.showModal({
          title: '数据错误',
          content: '接口:"' + url + 'api/wx/getdetail' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {
            wx.navigateBack({
              data: 1,
              fail(){
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            })
          },
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that=this;
    if (res.from === 'button') {
 
    }
    return {
      title: (that.data.user.uname?that.data.user.uname:that.data.user.nickName)+'邀请你加入'+that.data.detail.title,
      path: '/pages/detail/detail?id=' + that.data.detail.did,
      imageUrl:that.data.imgList[0].url,
      success: function (res) {
        console.log('成功', res)
      }
    }
  },
  onShareTimeline(){
    let that=this;
    return {
      title: (that.data.user.uname?that.data.user.uname:that.data.user.nickName)+'邀请你加入'+that.data.detail.title,
      query:'/pages/detail/detail?id=' + that.data.detail.did,
      imageUrl:that.data.imgList[0].url,
    }
  }
})